var prefix = jsctx + "/inviteTicket";

var inviteTicketList = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;
    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/inviteTicketList",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageSize: 10,
                pageList: [10,20,30],
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                paginationShowPageGo: true,
                height: h,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        beginTime: $('#beginTime').val(),
                        endTime: $('#endTime').val()
                        // mobile: $("#mobile").val().trim()
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '#',
                        width: '50', align: 'left',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'inviteName', title: '活动名称', align: 'left', width: '100'},
                    {field: 'inviteType', title: '奖励类型', align: 'left', width: '100'},
                    {field: 'gainType', title: '赠送对象', align: 'left', width: '100'},
                    {field: 'ticketDetail', title: '奖品', align: 'left', width: '120'},
                    {field: 'ticketTypeCount', title: '单次赠送数量', align: 'left', width: '100'},
                    {field: 'ticketName', title: '关联优惠券', align: 'left', width: '100'},
                    {field: 'inviteMemberCount', title: '成功邀请人数', align: 'left', width: '100'},
                    {field: 'ticketCount', title: '发放总量', align: 'left', width: '100'},
                    {field: 'beginTime', title: '开始时间', align: 'left', width: '100'},
                    {field: 'endTime', title: '结束时间', align: 'left', width: '100'},
                    {
                        field: 'status',
                        title: '活动状态',
                        width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (row.status == '0') {
                                return '已结束';
                            } else if (row.status == '1') {
                                return '进行中';
                            }else if(row.status == '2'){
                                return '未开始';
                            }else if(row.status == '3'){
                                return '已过期';
                            }
                        }
                    },
                    {
                        title: '操作',
                        field: 'inviteSettingId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            if(row.status == '1' || row.status == '2') {
                                var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="编辑" onclick="inviteTicketList.detailInviteTicket(\''
                                    + row.inviteSettingId
                                    + '\')">编辑</a> ';
                            }
                            if (row.status == '1') {
                                var b = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="结束" onclick="inviteTicketList.updateStatus(\''
                                    + row.inviteSettingId
                                    + '\')">结束</a> ';
                            }

                            var c = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="明细" onclick="inviteTicketList.inviteLink(\''
                                + row.inviteSettingId
                                + '\')">明细</a> ';

                            if (row.status == '0' || row.status == '3') {
                                return c;
                            } else if (row.status == '1') {
                                return a + b + c;
                            }else if(row.status == '2'){
                                return a + c;
                            }
                        }
                    }
                ]
            });
    };

    function addInviteTicket() {
        location.href = prefix + "/addInviteTicket";
    }

    function inviteLinkList(inviteSettingId) {
        location.href = prefix + "/inviteLink/index";
    }

    function timeingGiveAway(inviteSettingId) {
        location.href = prefix + "/timeingGiveAway/" + inviteSettingId;
    }

    function updateStatus(inviteSettingId) {
        layer.confirm('确定要结束活动？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'inviteSettingId': inviteSettingId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("结束成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function giveRecord(inviteSettingId) {
        location.href = prefix + "/giveRecord/" + inviteSettingId;
    }

    function getRecord(inviteSettingId) {
        location.href = prefix + "/getRecord/" + inviteSettingId;
    }

    function detailInviteTicket(inviteSettingId) {
        location.href = prefix + "/detailInviteTicket/" + inviteSettingId;
    }

    function sendRecord(inviteSettingId) {
        location.href = prefix + "/sendRecord/" + inviteSettingId;
    }

    function inviteLink(inviteSettingId) {
        location.href = prefix + "/inviteLink/" + inviteSettingId;
    }

    return {
        init: init,
        reLoad: reLoad,
        addInviteTicket:addInviteTicket,
        updateStatus: updateStatus,
        inviteLink: inviteLink,
        // inviteLinkList: inviteLinkList,
        timeingGiveAway: timeingGiveAway,
        getRecord: getRecord,
        giveRecord: giveRecord,
        detailInviteTicket: detailInviteTicket,
        sendRecord: sendRecord
    };
})();


var addInviteTicket = (function () {
        function init() {
            $("input[name='discountAmount']").blur(function () {
                if ($(this).val()) {
                    $(".couponError").remove()
                }
            })
            $("input[name='discount']").blur(function () {
                if ($(this).val()) {
                    $(".couponError").remove()
                }
            })

            validateRule();
        };

        function getCheckedRoles() {
            var adIds = "";
            $("input:checkbox[name=role]:checked").each(function (i) {
                if (0 == i) {
                    adIds = $(this).val();
                } else {
                    adIds += ("," + $(this).val());
                }
            });
            return adIds;
        }


        function save() {
            $("#roleIds").val(getCheckedRoles());

            var formData = new FormData($("#frmTenantTicketType")[0]);
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateMemberInviteSetting",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                }
            });
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmTenantTicketType").validate({
                rules: {
                    inviteName: {
                        required: true
                    },
                    ticketTypeCount: {
                        required: true,
                        digits: true,
                        min: 1,
                    },
                    ruleRemark: {
                        required: true,
                        maxlength: 500,
                    },
                    inviteRemark: {
                        required: true,
                        maxlength: 100,
                    },
                    beginTime: {
                        required: true,
                    },
                    endTime: {
                        required: true,
                    }
                },
                messages: {
                    inviteName: {
                        required: icon + "请输入活动名称"
                    }
                    ,
                    ticketTypeCount: {
                        required: icon + "请输入赠送数量",
                        digits: icon + "请输入大于0的正整数字",
                        min: icon + "请输入大于0的正整数字",
                    }
                    ,
                    ruleRemark: {
                        required: icon + "请输入活动规则描述",
                        maxlength:  icon + "请输入小于500字",
                    }
                    ,
                    inviteRemark: {
                        required: icon + "请输入活动邀请描述",
                        maxlength:  icon + "请输入小于100字",
                    },
                    beginTime: {
                        required: icon + "请选择活动开始时间",
                    }
                    ,
                    endTime: {
                        required: icon + "请选择活动结束时间",
                    },
                }
                ,
                submitHandler: function (form) {
                    save();
                }
            })
        }

        return {
            init: init
        };
    }

)();


var giveAway = (function () {

    /*------  验证码  -----*/
    var num1 = 60;
    var ajaxReady = true;

    function getTicketAuthCode() {
        if (ajaxReady) {
            $.ajax({
                url: prefix + "/getTicketAuthCode",
                type: "POST",
                data: {},
                beforeSend: function () {
                    ajaxReady = false;
                },
                success: function (data) {
                    if (data.status == 200) {
                        time();

                        function time() {
                            if (num1 == 0) {
                                $('#verificationCode').attr("disabled", "disabled")
                                $('#sendVerificationCode').text("获取验证码");
                                $('#sendVerificationCode').attr("onclick", 'giveAway.getTicketAuthCode()');
                                ajaxReady = true;
                                num1 = 60;
                            } else {
                                $('#verificationCode').removeAttr('disabled')
                                $('#sendVerificationCode').html(num1 + "秒后重试");
                                $('#sendVerificationCode').removeAttr('onclick');
                                num1--;
                                setTimeout(function () {
                                    time()
                                }, 1000)
                            }
                        }
                    } else {
                        parent.layer.alert(data.message);
                        ajaxReady = true;
                    }

                }
            })


        }
    }


    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {
            var formData = new FormData($("#frmGiveAway")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateMemberInviteSetting",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (data) {
                    isajaxsend = true
                    parent.layer.alert(data.message);
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmGiveAway").validate({
            rules: {
                sendCount: {
                    digits: true,
                    min: 0
                },
                ticketScheduleCount: {
                    digits: true,
                    min: 0
                },
                sendNum: {
                    digits: true,
                    min: 0
                },
                verificationCode: {
                    required: true,
                }

            },
            messages: {
                sendCount: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                ticketScheduleCount: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                sendNum: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                verificationCode: {
                    required: icon + "请输入验证码"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init,
        getTicketAuthCode: getTicketAuthCode
    };
})();

